package LeetCode;

import java.util.Deque;
import java.util.LinkedList;

public class LC_682_BaseballGame {

    public static void main(String[] args) {

    }

    class Solution {
        public int calPoints(String[] ops) {
            int sum = 0;
            if (ops.length == 0) return sum;
            Deque<Integer> stack = new LinkedList<>();
            for (String op : ops) {
                if (op.matches("-?\\d+(\\.\\d+)?")) {
                    int val = Integer.valueOf(op);
                    stack.addLast(val);
                    sum += val;
                } else if (op.equals("+")) {
                    int lastOne = 0, lastTwo = 0;
                    if (stack.size() != 0) {
                        lastOne = stack.removeLast();
                        if (stack.size() != 0) lastTwo = stack.peekLast();
                        stack.addLast(lastOne);
                    }
                    stack.addLast(lastOne + lastTwo);
                    sum += lastOne + lastTwo;
                } else if (op.equals("D")) {
                    if (stack.size() != 0) {
                        sum += stack.peekLast() * 2;
                        stack.addLast(stack.peekLast() * 2);
                    }
                } else {
                    if (stack.size() != 0) {
                        sum -= stack.removeLast();
                    }
                }
            }
            return sum;
        }
    }

}